package DoAn;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class ReadWriteFile {

	String filename = "E:/Program Files/Games/QuanLyNhanVien.dat";
	ObjectOutputStream write;
	ObjectInputStream read;
	
	public ReadWriteFile(){
		this.filename = "E:/Program Files/Games/QuanLyNhanVien.dat";
		//write = new ObjectOutputStream(new FileOutputStream(filename));
	}
	
	public ReadWriteFile(String fath){
		this.filename = fath;
		//write = new ObjectOutputStream(new FileOutputStream(filename));
	}
	
	public int getSL(){
		int sl = 0;
		try {
			read = new ObjectInputStream(new FileInputStream(filename));
			NhanVien r = new NhanVien();
			try {
				boolean c = true;
				while(c){
					try{
						r = (NhanVien)read.readObject();
						sl++;
					}catch (Exception e) {
						c = false;
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();sl--;
			}
			
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try{
			read.close();
		}catch (IOException e) { 
			e.printStackTrace();
		}
		
		return sl;
	}
	
	public NhanVien[] getDSNV(){
		int n = getSL();
		if(n == 0){
			return null;
		}
		else{
			NhanVien[] a = new NhanVien[n];		
			try {
				read = new ObjectInputStream(new FileInputStream(filename));			
				try {
					for(int i = 0; i < n; i++){
						a[i] = (NhanVien)(read.readObject());
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
			try{
				read.close();
			}catch (IOException e) { 
				e.printStackTrace();
			}
			
			return a;
		}
	}

	public String Read_In_NV(){
		NhanVien[] NV = getDSNV();
		String resuft = "";
		for(int i = 0; i < NV.length; i++){
			resuft += "\nSinh viên thứ " + (i+1) + ":";
			resuft += NV[i].GetNV();
		}		
		return resuft;
	}

	public void Save(NhanVien[] NV){
		try {
			write = new ObjectOutputStream(new FileOutputStream(filename));
			for(int i = 0; i < NV.length; i++){	
				write.writeObject(NV[i]);
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try{
			write.close();
		}catch (IOException e) { 
			e.printStackTrace();
		}
	}

}
